<?php
/**
 * [商网通 System] Copyright swtshop.cn
 * QQ: 1170787711
 * Author: gj.name
 * This is NOT a freeware
*/
defined('IN_UQ') or exit('Access Denied');
class express_mod extends module
{
    function __construct()
    {
        $this->spid = @$_SESSION['shop']['spid'];
        parent::__construct();
    }
    function get_tpl($spid)
    {
        $all = $this->db->get_all("select * from " . table('shop_express') . " where shop_id = " . $spid);
        if ($all) {
            foreach ($all as $v) {
                $data[] = $v;
            }
            return $data;
        }
    }
    function get_price($tpl_arr = array(), $area_id = null)
    {
        if ($tpl_arr) {
            $tpl_in = implode(',', $tpl_arr);
            $eall = $this->db->get_all("select * from " . table('shop_express') . " where id in (" . $tpl_in . ")");
            if ($eall) {
                foreach ($eall as $v) {
                    $sp_tpl[$v['shop_id']][] = $v['price'];
                }
                foreach ($sp_tpl as $k => $v) {
                    $aa[$k] = max($v);
                }
                return $aa;
            }
        }
    }
    function apply_code($code)
    {
        if ($code == 'uqcms') {
            $setarr['shop_id'] = $this->spid;
            $setarr['order_status'] = '1';
            $setarr['status'] = '1';
            $setarr['addtime'] = time();
            $query = $this->db->add(table('express'), $setarr);
            if ($query) {
                $code = $this->db->insert_id();
                return $code;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
    function get_config($code, $field = 'id')
    {
        $result = $this->db->get_all("select * from " . table('api_express') . " order by id desc");
        if ($result) {
            foreach ($result as $k => $v) {
                $data[$v[$field]] = $v;
            }
            if (isset($data[$code])) {
                return $data[$code];
            } else {
                return $data;
            }
        }
    }
    function get_code($code, $bill_row)
    {
        $result = $this->get_config($code, 'code');
        $file = FRAME_PATH . 'class/express/express_' . $code . '.class.php';
        if (is_file($file)) {
            include $file;
        } else {
            exit('file is exist');
        }
        $express_alias = 'express_' . $code;
        $config_param = unserialize($result['pcon']);
        $express = new $express_alias($config_param);
        return $express->get_code($bill_row);
    }
    function knn_send($kd_cfg, $pro_row)
    {
        $this->EBusinessID = cfg('express_appid');
        $this->AppKey = cfg('express_appkey');
        $this->ReqURL = 'http://testapi.kdniao.cc:8081/api/Eorderservice';
        $eorder = array();
        $eorder["OrderCode"] = $pro_row['bill_no'];
        $eorder["ShipperCode"] = $kd_cfg['code'];
        if (!empty($pro_row['logistic_code'])) {
            $eorder["LogisticCode"] = $pro_row['logistic_code'];
        }
        $eorder["PayType"] = 1;
        $eorder["ExpType"] = 1;
        $eorder["IsNotice"] = '1';
        if (!empty($kd_cfg['username'])) {
            $eorder["CustomerName"] = $kd_cfg['username'];
        }
        if (!empty($kd_cfg['password'])) {
            $eorder["CustomerPwd"] = $kd_cfg['password'];
        }
        if (!empty($kd_cfg['month_code'])) {
            $eorder["MonthCode"] = $kd_cfg['month_code'];
        }
        if (!empty($kd_cfg['site_code'])) {
            $eorder["SendSite"] = $kd_cfg['site_code'];
        }
        $eorder["Receiver"] = array('Name' => $pro_row['receive']['name'], 'Mobile' => $pro_row['receive']['mobile'], 'ProvinceName' => $pro_row['receive']['prov_cn'], 'CityName' => $pro_row['receive']['city_cn'], 'ExpAreaName' => $pro_row['receive']['dist_cn'], 'Address' => $pro_row['receive']['address']);
        $eorder["Sender"] = array('Name' => $pro_row['send']['name'], 'Mobile' => $pro_row['send']['mobile'], 'ProvinceName' => $pro_row['send']['prov_cn'], 'CityName' => $pro_row['send']['city_cn'], 'ExpAreaName' => $pro_row['send']['dist_cn'], 'Address' => $pro_row['send']['address']);
        $eorder["Commodity"] = array(array('GoodsName' => '其他'));
        $eorder["IsReturnPrintTemplate"] = '1';
        $jsonParam = $this->json_utf8($eorder);
        $jsonResult = $this->submitEOrder($jsonParam);
        $result = json_decode($jsonResult, true);
        if ($result["ResultCode"] == "100") {
            if ($result["Success"]) {
                $data['logistic_code'] = $result['Order']['LogisticCode'];
                $data['print_tpl'] = $result['PrintTemplate'];
                return $data;
            } else {
                return $result;
            }
        } else {
            return $jsonResult;
        }
    }
    function json_utf8($value)
    {
        if (version_compare(PHP_VERSION, '5.4.0', '<')) {
            $str = json_encode($value);
            $str = preg_replace_callback("#\\\\u([0-9a-f]{4})#i", function ($matchs) {
                return iconv('UCS-2BE', 'UTF-8', pack('H4', $matchs[1]));
            }, $str);
            return $str;
        } else {
            return json_encode($value, JSON_UNESCAPED_UNICODE);
        }
    }
    function submitEOrder($requestData)
    {
        $datas = array('RequestData' => urlencode($requestData), 'EBusinessID' => $this->EBusinessID, 'RequestType' => '1007', 'DataType' => '2');
        $datas['DataSign'] = $this->encrypt($requestData, $this->AppKey);
        $result = $this->sendPost($this->ReqURL, $datas);
        return $result;
    }
    function sendPost($url, $datas)
    {
        $temps = array();
        foreach ($datas as $key => $value) {
            $temps[] = sprintf('%s=%s', $key, $value);
        }
        $post_data = implode('&', $temps);
        $url_info = parse_url($url);
        if (empty($url_info['port'])) {
            $url_info['port'] = 80;
        }
        $httpheader = "POST " . $url_info['path'] . " HTTP/1.0\r\n";
        $httpheader .= "Host:" . $url_info['host'] . "\r\n";
        $httpheader .= "Content-Type:application/x-www-form-urlencoded\r\n";
        $httpheader .= "Content-Length:" . strlen($post_data) . "\r\n";
        $httpheader .= "Connection:close\r\n\r\n";
        $httpheader .= $post_data;
        $fd = fsockopen($url_info['host'], $url_info['port']);
        fwrite($fd, $httpheader);
        $gets = "";
        $headerFlag = true;
        while (!feof($fd)) {
            if (($header = @fgets($fd)) && ($header == "\r\n" || $header == "\n")) {
                break;
            }
        }
        while (!feof($fd)) {
            $gets .= fread($fd, 128);
        }
        fclose($fd);
        return $gets;
    }
    function encrypt($data, $appkey)
    {
        return urlencode(base64_encode(md5($data . $appkey)));
    }
    function so($code, $nu)
    {
        $callbackMark = 'jQuery1930015837112441658974_' . getMillisecond();
        $url = 'https://open.onebox.so.com/api/getkuaidi?callback=' . $callbackMark . '&com=' . $code . '&nu=' . $nu . '&_=' . getMillisecond();
        $response = curl::get($url);
        $lpos = strpos($response, "(");
        $rpos = strrpos($response, ")");
        $response = substr($response, $lpos + 1, $rpos - $lpos - 1);
        $data = json_decode($response);
        $result = $data->data->data;
        foreach ($result as $key => $val) {
            $myData[] = array('msg' => $val->context, 'time' => $val->time);
        }
        return $myData;
    }
}